<template>
	<div class="about">
		<h1>轮播图片列表</h1>
		<el-button type="primary" @click="addPicture">添加图片</el-button>
		
		<draggable v-model="items" @update="datadragEnd" class="wrapper">
			<div v-for="element in items" :key="element.id">
				
				<el-card shadow="hover" style="margin-left:5px" class="box-card">
					<span v-text="element.index"></span><br>
					<el-button type="text"  @click="uploadDialog(element)">编辑</el-button>
					<el-button type="text"  @click="remove(element)">删除</el-button>
					<el-image :src="element.picture" alt="图片加载失败"/>
					<span label="介绍">{{element.intro}}</span>
				
				</el-card>
				
				</div>
		</draggable>
		<el-dialog
			title="提示"
			:visible.sync="dialogVisible"
			width="30%"
			@close='closeDialog'>
			<div>
				<el-upload class="avatar-uploader" :action=qiniuUrl
					:http-request = this.$qiniu
					:headers="getAuthHeaders()" :show-file-list="false"
					:before-upload="beforeUpload">
					<el-image v-if="model.picture" :src="model.picture" class="avatar"/>
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
				
					<el-input
					type="textarea"
					placeholder="请输入内容"
					v-model="model.intro"
					maxlength="30"
					show-word-limit
					>
					</el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="save">确 定</el-button>
			</span>
			</div>
		</el-dialog>
	</div>


</template>


<script>
import draggable from 'vuedraggable'
	export default {
		components: {draggable},
		data() {
			return {
				show:false,
				items: [],
				dialogVisible: false,
				//这是根据你七牛云创建空间时所选择的地区
				qiniuUrl : 'https://upload-z2.qiniup.com',
				model: {
					picture:'',
					intro:'',
					id:''
				},
			}
		},

		methods: {
			async fetch() {
					const res = await this.$http.get('rest/rotate')
					console.log(res.data)
					this.items = res.data
			},
			async remove(element) {
				this.$confirm(`此操作将永久删除该照片${element.name}, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					await this.$http.get('minus/Rotate')
					await this.$http.delete(`rest/rotate/${element._id}`)
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.fetch()
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			uploadDialog(element){
				this.dialogVisible = true;
				this.model.picture = element.picture;
				this.model.intro = element.intro
				this.model.id = element._id
			},
			async datadragEnd(evt) {
				evt.preventDefault();
				console.log(evt)
				console.log('拖动前的索引 :' + evt.oldIndex)
				console.log('拖动后的索引 :' + evt.newIndex)
				// 遍历数组,将索引值赋值到对应的sort_order上面,完成排序
				let arr = this.items;
				let newArr = await arr.map((item, i) => {
					return {
					sort_order: i+1,
					id: item._id
					};
				});
				console.log(newArr)
				for(var m=0;m<newArr.length;m++){
					if(newArr[m].id == this.items[m]._id){
						this.items[m].index = newArr[m].sort_order
						const model = {
							index:this.items.index,
							intro: this.items.intro,
							picture: this.items.picture,
						}
						const res = await this.$http.put(`rest/rotate/${newArr[m].id}`, model)
						console.log(res)
					}
				}
			}, 

			async save() {
				let res
				console.log(this.model.id)
				if (this.model.intro == null || this.model.intro.length == 0) {
					this.$message({
						type: 'warning',
						message: '介绍内容不能为空'
					})
				} else {
					if (this.model.id) {
						// 编辑
						res = await this.$http.put(`rest/rotate/${this.model.id}`, this.model)
						console.log(res.data)
						this.$message({
							type: 'success',
							message: '保存成功'

						})
						this.dialogVisible = false
					}
				}
			},

			async addPicture(){
				const res1 = await this.$http.get('add/Rotate')
				const model ={
					picture:'',
					intro:'请上传图片',
					index:res1.data.count
				}
				console.log(model.index)
				//新建
				const res2 = await this.$http.post('rest/rotate', model)
				this.$message({
					type: 'success',
					message: '新建成功！'
				})
				
				this.items.push(res2.data)
				this.model = res2.data
				this.uploadDialog(this.model)
			},

			closeDialog(){
				this.model ={
					picture:'',
					intro:'',
					id:''
				}
			},

			// 验证文件合法性
			beforeUpload (file) {
			const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
			const isLt2M = file.size / 1024 / 1024 < 2
			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!')
			}
			return isJPG && isLt2M
			}
		},
		created() {
			this.fetch()
		},
		computed: {
			//这里需要把store动态的数据放到computed里面才会同步更新视图
            getPicture(){
				console.log(this.$store.state.carousel_picture)
                return this.$store.state.carousel_picture
            }
		},
		watch:{
			getPicture(n){
				this.model.picture = n
				console.log(n)
			}
		}
	}
</script>

<style>
.wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
}

</style>
